package com.spbdx.web.controller.common;

import com.google.code.kaptcha.Producer;
import com.spbdx.common.annotation.Log;
import com.spbdx.common.config.CmsConfig;
import com.spbdx.common.constant.CacheConstants;
import com.spbdx.common.constant.Constants;
import com.spbdx.common.core.domain.AjaxResult;
import com.spbdx.common.core.domain.entity.SysMenu;
import com.spbdx.common.core.domain.entity.SysUser;
import com.spbdx.common.core.domain.model.LoginBody;
import com.spbdx.common.core.redis.RedisCache;
import com.spbdx.common.enums.BusinessType;
import com.spbdx.common.exception.ServiceException;
import com.spbdx.common.utils.RandomUtil;
import com.spbdx.common.utils.SecurityUtils;
import com.spbdx.common.utils.StringUtils;
import com.spbdx.common.utils.sign.Base64;
import com.spbdx.common.utils.sms.SmsUtil;
import com.spbdx.common.utils.uuid.IdUtils;
import com.spbdx.framework.web.service.SysLoginService;
import com.spbdx.framework.web.service.SysPermissionService;
import com.spbdx.system.domain.dto.AppCodeDto;
import com.spbdx.system.mapper.SysUserMapper;
import com.spbdx.system.service.ISysConfigService;
import com.spbdx.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 登录验证
 *
 * @author cms
 */
@Api(tags = "登录管理")
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private RedisCache redisCache;

    private static SmsUtil smsUtil;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private ISysConfigService configService;

    @Value("${sms.sign}")
    private String smsSign;

    // 2. 在此处赋值，在OnMessage或其他的方法里就可以通过redisService.get()...使用了
    @Autowired
    public void setRedisService(SmsUtil smsUtil) {
        SysLoginController.smsUtil = smsUtil;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("账号密码登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation("获取路由信息")
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("手机号验证码登录")
    @Log(title = "短信登录", businessType = BusinessType.INSERT)
    @PostMapping("/loginTel")
    public AjaxResult loginTel(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginTel(loginBody);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 发送验证码
     *
     * @param appCodeDTO 登录信息
     * @return 结果
     */
    @ApiOperation("获取手机短信验证码")
    @PostMapping("/appCaptcha")
    public AjaxResult getAppCode(@RequestBody AppCodeDto appCodeDTO) throws Exception {
        String phone = appCodeDTO.getPhone();
        if (!Pattern.compile("^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$").matcher(phone).matches()) {
            throw new ServiceException("发送失败,手机号格式不正确!");
        }
        SysUser sysUser = userMapper.checkPhoneUnique(phone);
        if (Objects.isNull(sysUser)) {
            return AjaxResult.error("系统不存在该手机号，请重试！");
        }
        String codeKey = CacheConstants.CAPTCHA_CODE_KEY + phone;
        String value = redisCache.getCacheObject(codeKey);
        if (StringUtils.isNotEmpty(value)) {
            return AjaxResult.error("请勿重复发送验证码！");
        }

        // 保存验证码信息
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + phone;
        // 生成四位数验证码
        String code = RandomUtil.getRandomNumString(6);
        try {
            String content = "【" + smsSign + "】验证码" + code + ",5分钟内有效。请勿告知他人,谨防上当受骗。";
            smsUtil.send(Arrays.asList(phone), content, "");
        } catch (Exception e) {
            return AjaxResult.error("发送失败" + e);
        }
        //把验证码答应存入缓存，5分钟的时间
        redisCache.setCacheObject(verifyKey, code, Constants.CODE_EXPIRATION, TimeUnit.MINUTES);
        //把信息封装返回
        return AjaxResult.success();
    }

    /**
     * 生成验证码
     */
    @ApiOperation("获取验证码")
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = CmsConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
}
